import { loc } from '../../local';

const wrong_reg = (data, reg, info) => {
    if (reg.test(data)) {
        return null;
    }

    return `${data}: ${info}`;
};

const ascii_print = (data) => {
    return wrong_reg(data, /^[\x20-\x7E]*$/, loc("ckas"));
};

const ck_empty = (val, info) => {
    let v = val;
    if (v) {
        v = v.trim();
    }

    if (v) {
        return null;
    }

    if (info) {
        return info;
    }

    return loc("bnwk");
};

const ck_ascii = (v, info) => {
    if (!v) {
        return info;
    }

    const tmp = v.trim();
    if (!tmp) {
        return info;
    }

    let r = ascii_print(tmp);
    if (r) {
        return r;
    }

    return null;
};

const ckNum = (d, dmax=null, alertNull=true, pre="", zero=false) => {
    if (!d) {
        if (alertNull) {
            return [null, pre + loc("bnwk")];
        }
    }

    const num = parseInt(d, 10);
    if (!num && num !== 0) {
        return [null, pre + loc("ckn0")];
    }

    const n = num + "";
    const tmp = d + "";
    if (n.length !== tmp.length) {
        return [null, pre + loc("ckn1")];
    }

    if (num <= 0 && !zero) {
        return [null, pre + loc("ckn2")];
    }

    if (dmax && num > dmax) {
        return [null, pre + loc("ckn3") + dmax];
    }

    return [num, null];
};

const ck_num = (v, info) => {
    const [, err] = ckNum(v, null, true, info);
    if (err) {
        return err;
    }

    return null;
};

const ck_num_empty = (v, info="") => {
    if (!v) {
        return info;
    }

    return ck_num(v, info);
};

const ck_date = (v) => {
    if (!v) {
        return loc("ckd");
    }

    const r = v.getTime();
    if (!r) {
        return loc("ckd");
    }

    return null;
};

const ck_date_range = (start, end) => {
    const r = ck_date(end);
    if (r) {
        return r;
    }

    if (start > end) {
        return loc("ckr");
    }

    return null;
};

const ck_type = (data, type) => {
    const s = data.slice(0, type.length);
    if (type !== s) {
        return `${loc("ckt0")} ${type}_x.xx.tar.gz`;
    }

    const e = data.slice(type.length);

    return wrong_reg(e, /^_[0-9]+\.[0-9]+\.tar\.gz$/, `${loc("ckt1")} ${type}_x.xx.tar.gz`);
};

const ck_ascii_len = (v, len, info) => {
    const r = ck_ascii(v, info);
    if (r) {
        return r;
    }

    if (len && v.length !== len) {
        return `${loc("cdw")}${len}`;
    }

    return null;
};

const ck_float = (v, info="") => {
    const e = parseFloat(v);
    if (isNaN(e)) {
        return info + loc("ckn0");
    }

    return null;
};

const ck_int = (v, info="") => {
    const e = parseInt(v, 10);
    if (isNaN(e)) {
        return info + loc("ckn0");
    }

    return null;
};

export {ck_int, ck_float, ck_ascii_len, ckNum, ck_type, ck_num_empty, ck_date, ck_date_range, ck_num, ck_empty, ck_ascii, wrong_reg, ascii_print};
